package com.sc.sc250601.cook.job;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.sc250601.cook.mapper.RecipeMapper;
import com.sc.sc250601.cook.pojo.Recipe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import lombok.extern.log4j.Log4j2;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Log4j2
@Component
public class WeekTopScheduler {

    @Autowired
    private RecipeMapper recipeMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 每隔5分钟刷新一次本周最热菜谱缓存
     */
    //@Scheduled(fixedRate = 5 * 60 * 1000) // 每5分钟执行一次
    @Scheduled(cron = "0 0/1 * * * ?") // 每1分钟执行一次
    public void refreshWeekTopCache() {
        String topKey = "cook:recipe:weekTop";
        try {
            // SQL 已经按权重排序
            List<Recipe> recipesTop = recipeMapper.weekTop2();
            if (recipesTop != null && !recipesTop.isEmpty()) {
                redisTemplate.opsForValue().set(
                        topKey,
                        mapper.writeValueAsString(recipesTop),10, TimeUnit.MINUTES);
                // 如果你希望TTL，就加第三个参数：10, TimeUnit.MINUTES
            } else {
                // 没有数据就清空缓存
                redisTemplate.delete(topKey);
            }
            log.info("WeekTop cache refreshed, size={}", recipesTop.size());
        } catch (Exception e) {
            log.error("Failed to refresh weekTop cache", e);
        }
    }
}